/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import rentaldb.Provider;

/**
 *
 * @author Pop
 */
public class ProviderDao {
    private EntityManager em;
    private EntityManagerFactory emf;
    
    public ProviderDao(){
        try{
            emf = Persistence.createEntityManagerFactory("RentaldbPU");
            em = emf.createEntityManager();  
        }catch(Exception e){ System.out.println(e);}
    }
    
    public void persist(Provider p){
        em.getTransaction().begin();
        em.persist(p);
        em.getTransaction().commit();
        
    }
    
    public void update(Provider p){
        em.getTransaction().begin();
        em.merge(p);
        em.getTransaction().commit();
    }
    
    public void delete(Provider p) throws Exception{
        p = getProviderById(p.getProviderId());
        em.getTransaction().begin();
        em.remove(p);
        em.getTransaction().commit();
    }
    
    public Provider getProviderById(Integer id) throws Exception{
        //em.createQuery("select * from property");
        Query q = em.createNamedQuery("Provider.findByProviderId");
        q.setParameter("providerId", id);
        Provider p = (Provider)q.getSingleResult();
        
        return p;
    }
    
    public List<Provider> getAllProviders() throws Exception{
        Query q = em.createNamedQuery("Provider.findAll");
        List<Provider> providerList = q.getResultList();
        
        return providerList;
    }
}

